package com.ahncnk.powermonitor.admin.auth.domain.dto;

import javax.servlet.http.Cookie;
import java.time.Duration;

/**
 * 双cookie的jwt.
 *
 * @author lipei
 */
public class Token {
    /**
     * JavaScript 可访问的cookie. 存有 header.payload 信息。
     */
    private final Cookie payload;
    /**
     * 会话Cookie，JavaScript不可访问. 存有 signature 信息。
     */
    private final Cookie signature;

    public Token(String jwt, String appName, Duration age) {
        payload = new Cookie(headerAndPayloadCookieName(appName), jwt.substring(0, jwt.lastIndexOf('.')));
        payload.setPath("/");
        payload.setMaxAge((int) age.getSeconds());

        signature = new Cookie(signatureCookieName(appName), jwt.substring(jwt.lastIndexOf('.') + 1));
        signature.setPath("/");
        signature.setHttpOnly(true);
    }

    /**
     * JavaScript 可访问的cookie. 存有 header.payload 信息。
     */
    public Cookie getPayload() {
        return payload;
    }


    /**
     * 会话Cookie，JavaScript不可访问. 存有 signature 信息。
     */
    public Cookie getSignature() {
        return signature;
    }

    /**
     * 存放 header.payload 信息的cookie名.
     */
    public static String headerAndPayloadCookieName(String appName) {
        return appName + "-authentication";
    }

    /**
     * 存放 signature 信息的cookie名.
     */
    public static String signatureCookieName(String appName) {
        return appName + "-signature";
    }
}
